<template>
  <div>

    <div class="container">
      <div class="handle-box">
        <el-input v-model="query.name" clearable placeholder="地点/美食名称" style="width: 200px;" class="handle-input mr10"></el-input>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        <el-button type="primary" icon="el-icon-plus" @click="addVisible = true">新增</el-button>
        <!-- ✅ 导入导出按钮 -->
        <el-button type="danger" icon="el-icon-delete" @click="handleBatchDelete" :disabled="multipleSelection.length === 0">批量删除</el-button>
      </div>

      <el-table
        :data="tableData"
        border
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column prop="conferences.conferenceName" label="所属会议名称"></el-table-column>
        <el-table-column
          prop="pointType"
          label="地点类型"
          :formatter="(row) => {
            const map = {
              conference_location: '会议地点',
              landmark: '周边景观',
              food: '特色美食'
            };
            return map[row.pointType] || '-';
          }"
        />
        <el-table-column prop="name" label="地点名称"></el-table-column>
        <!-- <el-table-column prop="latitude" label="纬度"></el-table-column>
        <el-table-column prop="longitude" label="经度"></el-table-column> -->
        <el-table-column prop="description" label="介绍"></el-table-column>
        <el-table-column prop="address" label="地址"></el-table-column>
        <el-table-column label="图片">
          <template slot-scope="scope">
            <el-image
              style="width: 100px; height: 100px"
              :src="scope.row.imageUrl"
              :preview-src-list="[scope.row.imageUrl]"
              fit="cover"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              icon="el-icon-edit"
              @click="handleEdit(scope.row)"
            >编辑</el-button>
            <el-button
              type="text"
              icon="el-icon-delete"
              class="red"
              @click="handleDelete(scope.row.pointId)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :current-page="query.pageIndex"
          :page-size="query.pageSize"
          :total="pageTotal"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </div>

    <!-- 编辑弹出框 -->
    <el-dialog title="编辑地点" :visible.sync="editVisible" width="40%">
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入地点/美食名称" />
        </el-form-item>
      
        <el-form-item label="类型" prop="pointType">
          <el-select v-model="form.pointType" placeholder="请选择地点/美食类型">
            <el-option label="会议地点" value="conference_location" />
            <el-option label="周边景观" value="landmark" />
            <el-option label="特色美食" value="food" />
          </el-select>
        </el-form-item>
      
        <el-form-item label="纬度" v-show="false" >
          <el-input v-model="form.latitude" placeholder="请输入纬度" />
        </el-form-item>
      
        <el-form-item label="经度" v-show="false">
          <el-input v-model="form.longitude" placeholder="请输入经度" />
        </el-form-item>
      
        <el-form-item label="地址" prop="address">
          <el-input
            v-model="form.address"
            placeholder="请输入详细地址"
            @blur="fetchCoordinates(form.address, 'form')"
          />
        </el-form-item>
      
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" v-model="form.description" placeholder="请输入描述信息" />
        </el-form-item>
      
        <el-form-item label="上传图片" prop="imageList">
          <el-upload
            action="#"
            :http-request="uploadToOSS"
            list-type="picture-card"
            :file-list="form.imageList"
            :on-remove="handleImageRemove"
            :on-preview="handleImagePreview"
            multiple
            ref="upload"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-form>
    
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelEdit">取 消</el-button>
        <el-button type="primary" @click="saveEdit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 新增弹出框 -->
    <el-dialog title="新增" :visible.sync="addVisible" width="40%">
      <el-form
        ref="form"
        :model="addForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="会议名称" prop="conferenceId">
          <el-select v-model="addForm.conferenceId" placeholder="请选择会议名称">
            <el-option
              v-for="item in conferences"
              :key="item.conferenceId"
              :label="item.conferenceName"
              :value="item.conferenceId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入地点/美食名称" />
        </el-form-item>
      
        <el-form-item label="类型" prop="pointType">
          <el-select v-model="addForm.pointType" placeholder="请选择地点/美食类型">
            <el-option label="会议地点" value="conference_location" />
            <el-option label="周边景观" value="landmark" />
            <el-option label="特色美食" value="food" />
          </el-select>
        </el-form-item>
      
        <el-form-item label="纬度" v-show="false">
          <el-input v-model="addForm.latitude" placeholder="请输入纬度" />
        </el-form-item>
      
        <el-form-item label="经度" v-show="false">
          <el-input v-model="addForm.longitude" placeholder="请输入经度" />
        </el-form-item>
      
        <el-form-item label="地址" prop="address">
          <el-input
            v-model="addForm.address"
            placeholder="请输入详细地址"
            @blur="fetchCoordinates(addForm.address, 'addForm')"
          />
        </el-form-item>
      
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" v-model="addForm.description" placeholder="请输入描述信息" />
        </el-form-item>
      </el-form>
    
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelAdd">取 消</el-button>
        <el-button type="primary" @click="saveAdd">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible" width="50%">
      <img :src="dialogImageUrl" alt="" style="width: 100%" />
    </el-dialog>

  </div>
</template>

<script>
import * as XLSX from 'xlsx';
import requests from '../utils/request'
import dayjs from 'dayjs';


export default {
    name: 'basetable',
    data() {
      return {
        dialogImageUrl: '',
        dialogVisible: false,
        query: {
            name: '',
            pageIndex: 1,
            pageSize: 30
        },
        tableData: [],
        multipleSelection: [],
        exportData: [],
        editVisible: false,
        addVisible: false,
        pageTotal: 0,
        imgUrl:'',
        form: {
          name: '',
          pointType: '',
          latitude: '',
          conferenceId: null,
          longitude: '',
          address: '',
          description: '',
          imageUrl: '',
          imageList: []
        },
        conferences:{},
        addForm: {
          name: '',
          pointType: '',
          latitude: '',
          conferenceId: null,
          longitude: '',
          address: '',
          description: '',
        },
        idx: -1,
        id: -1,
        rules: {
          conferenceId: [
            { required: true, message: '请选择会议类型', trigger: 'change' }
          ],
          name: [
            { required: true, message: '请输入地点名称', trigger: 'blur' }
          ],
          pointType: [
            { required: true, message: '请选择地点类型', trigger: 'change' }
          ],
          latitude: [
            { required: true, message: '请输入纬度', trigger: 'blur' },
            { pattern: /^-?\d{1,3}(\.\d{1,7})?$/, message: '请输入合法的纬度（整数最多3位，小数最多7位）' }
          ],
          longitude: [
            { required: true, message: '请输入经度', trigger: 'blur' },
            { pattern: /^-?\d{1,3}(\.\d{1,7})?$/, message: '请输入合法的经度（整数最多3位，小数最多7位）' }
          ],
          address: [
            { required: true, message: '请输入地址', trigger: 'blur' }
          ],
          description: [
            { required: false }
          ],
          imageList: [
            { type: 'array', required: true, message: '请上传图片', trigger: 'change' }
          ]
        }
      };
    },
    watch: {
      'form.address'(newVal) {
        if (newVal && newVal.length > 3) {
          this.fetchCoordinates(newVal,'form');
        }
      },
      'addForm.address'(newVal) {
        if (newVal && newVal.length > 3) {
          this.fetchCoordinates(newVal, 'addForm');
        }
      }
    },
    created() {
       this.loading()
    },
    methods: {
      //加载数据
      loading() {
        requests.get("/mapPoints/pageSelect", {
          page: this.query.pageIndex,
          size: this.query.pageSize,
          name: this.query.name
        }).then(res=>{
          this.pageTotal = res.total,
          this.tableData = res.data
        });
        requests.get("/conferences/selectAll").then(res=>{
          this.conferences = res          
        })
      },
      // 触发搜索按钮
      handleSearch() {
          this.loading();
      },
      // 删除操作
      handleDelete(row) {
        // 二次确认删除
        this.$confirm('确定要删除吗？', '提示', {
            type: 'warning'
        })
            .then(() => {
                requests.delete("/mapPoints/delById",{
                  pointId: row
                }).then(res=>{
                  this.$message.success(res);
                  this.loading()
                })
            })
      },
      // 编辑操作
      handleEdit(row) {
        // 安全深拷贝 row 对象，避免响应式污染
        // 赋值给表单
        this.form = row;
        if (!this.form.imageList && this.form.imageUrl) {
          this.form.imageList = [{ name: '封面图.jpg', url: this.form.imageUrl }];
        } else if (!this.form.imageList) {
          this.form.imageList = [];
        }
        this.editVisible = true;
      },
      // 取消编辑
      cancelEdit() {
        // 失去当前聚焦
        document.activeElement && document.activeElement.blur();
      
        this.editVisible = false;
        // 重置表单（如果需要）
        this.$refs.form.resetFields();
      },
      // 保存编辑
      saveEdit() {
        // 先校验表单
        this.$refs.form.validate(valid => {
          if (!valid) {
            // 校验失败，不提交
            return;
          }
          this.form.imageUrl = this.imgUrl
          // 校验成功，调用接口
          requests.post("/mapPoints/edit", this.form)
            .then(res => {
              this.$message.success(res);  // 用 success 提示更合适
              this.editVisible = false;    // 请求成功后关闭弹窗
              this.loading();              // 刷新数据
              this.imgUrl = null
            })
        });
      },
      // 分页导航
      handlePageChange(val) {
          this.query.pageIndex = val
          this.loading()
      },
      // 单选、多选改变时调用
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      // 批量删除
      handleBatchDelete() {
        if (this.multipleSelection.length === 0) {
          this.$message.warning('请选择要删除的酒店');
          return;
        }
      
        this.$confirm(`确定删除这 ${this.multipleSelection.length} 项吗？`, '提示', {
          type: 'warning'
        })
          .then(() => {
            const ids = this.multipleSelection.map(item => item.pointId);
            console.log(ids);
            
            requests.post('/mapPoints/delByIds', ids)  // ✅ 注意这里直接传数组
              .then(res => {
                this.$message.success(res);
                this.loading(); // 重新加载表格
              })
          })
      },
      //新增操作
      handleAdd() {
        this.addVisible = true;
      },
      // 取消操作
      cancelAdd() {
        // 失去当前聚焦
        document.activeElement && document.activeElement.blur();
      
        this.addVisible = false;
        // 重置表单（如果需要）
        this.$refs.addForm.resetFields();
      },
      // 保存操作
      saveAdd() {
        // 先校验表单
        this.$refs.form.validate(valid => {
          if (!valid) {
            // 校验失败，不提交
            return;
          }
          
          // // 校验成功，调用接口
          requests.post("/mapPoints/add", this.addForm)
            .then(res => {
              this.$message.success(res);  // 用 success 提示更合适
              this.addVisible = false;    // 请求成功后关闭弹窗
              this.loading();              // 刷新数据
            })
        });
      },
      //图片上传
      // 上传至阿里云 OSS
      uploadToOSS(option) {
        const file = option.file;
      
        // 获取签名
        requests.get('/files/policy', {
          conferenceId: this.form.conferenceId
        }).then(res => {
          
          const data = res;
          const fileName = Date.now() + '-' + file.name;
          const key = data.dir + fileName;
          
          const formData = new FormData();
          formData.append('key', key);
          formData.append('policy', data.policy);
          formData.append('OSSAccessKeyId', data.accessid);
          formData.append('success_action_status', '200');
          formData.append('signature', data.signature);
          formData.append('file', file);
          
          // 上传到阿里云
          requests.post(data.host, formData).then(() => {
            const url = `${data.host}/${key}`;
            if (!this.form.imageList) {
              this.form.imageList = [];
            }
            this.form.imageList.push({ url });
            this.imgUrl = url
            // ✅ 触发校验
            this.$refs.form.validateField('imageList');
          
            this.$message.success('上传成功');
          })
        })
      },    
      // 移除图片（支持单张）
      handleImageRemove(file, fileList) {
        this.form.imageList = fileList;
      
        // ✅ 触发校验
        this.$refs.form.validateField('imageList');
      },
      // 预览图片
      handleImagePreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      //经纬度
      fetchCoordinates(address, targetFormKey = 'form') {
        const key = "e1587c72be372391a102e80580b4ad23";
        const encodedAddress = encodeURIComponent(address);
        const url = `https://restapi.amap.com/v3/geocode/geo?address=${encodedAddress}&key=${key}`;
      
        fetch(url)
          .then(res => res.json())
          .then(data => {
            if (data.geocodes && data.geocodes.length > 0) {
              const location = data.geocodes[0].location; // "经度,纬度"
              const [lng, lat] = location.split(",");
              this[targetFormKey].longitude = lng;
              this[targetFormKey].latitude = lat;
            } else {
              this.$message.warning("未找到匹配的经纬度，请检查地址");
            }
          })
          .catch(err => {
            console.error("获取地理编码失败", err);
            this.$message.error("请求失败，请检查网络或API Key");
          });
      },
  }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
